home *** CD-ROM | disk | FTP | other *** search
/ Ham Radio 2000 #2 / Ham Radio 2000 - Volume 2.iso / HAMV2 / TCP_IP / TNOS230S / UDPHDR.C < prev    next >
C/C++ Source or Header  |  1996-08-29  |  2KB  |  83 lines

  1. /* UDP header conversion routines
  2.  * Copyright 1991 Phil Karn, KA9Q
  3.  */
  4. #include "global.h"
  5. #include "mbuf.h"
  6. #include "ip.h"
  7. #include "udp.h"
  8.  
  9. #if !defined(_lint)
  10. static char rcsid[] OPTIONAL = "$Id: udphdr.c,v 1.8 1996/08/29 12:11:16 root Exp root $";
  11. #endif
  12.  
  13.  
  14. /* Convert UDP header in internal format to an mbuf in external format */
  15. struct mbuf *
  16. htonudp (udp, data, ph)
  17. struct udp *udp;
  18. struct mbuf *data;
  19. struct pseudo_header *ph;
  20. {
  21. struct mbuf *bp;
  22. register unsigned char *cp;
  23. int16 checksum;
  24.  
  25.     /* Allocate UDP protocol header and fill it in */
  26.     if ((bp = pushdown (data, UDPHDR)) == NULLBUF)
  27.         return NULLBUF;
  28.  
  29.     cp = bp->data;
  30.     cp = put16 (cp, udp->source);    /* Source port */
  31.     cp = put16 (cp, udp->dest);    /* Destination port */
  32.     cp = put16 (cp, udp->length);    /* Length */
  33.     *cp++ = 0;            /* Clear checksum */
  34.     *cp-- = 0;
  35.  
  36.     /* All zeros and all ones is equivalent in one's complement arithmetic;
  37.      * the spec requires us to change zeros into ones to distinguish an
  38.       * all-zero checksum from no checksum at all
  39.      */
  40.     if ((checksum = cksum (ph, bp, ph->length)) == 0)
  41. #ifdef __GNUC__
  42.         checksum = (int16)0xffffU;
  43. #else
  44.         checksum = (int16)0xfffff;
  45. #endif
  46.     (void) put16 (cp, checksum);
  47.     return bp;
  48. }
  49.  
  50.  
  51. /* Convert UDP header in mbuf to internal structure */
  52. int
  53. ntohudp (udp, bpp)
  54. struct udp *udp;
  55. struct mbuf **bpp;
  56. {
  57. char udpbuf[UDPHDR];
  58.  
  59.     if (pullup (bpp, (unsigned char *)udpbuf, UDPHDR) != UDPHDR)
  60.         return -1;
  61.     udp->source = get16 (&udpbuf[0]);
  62.     udp->dest = get16 (&udpbuf[2]);
  63.     udp->length = get16 (&udpbuf[4]);
  64.     udp->checksum = get16 (&udpbuf[6]);
  65.     return 0;
  66. }
  67.  
  68.  
  69. /* Extract UDP checksum value from a network-format header without
  70.  * disturbing the header
  71.  */
  72. int16
  73. udpcksum (bp)
  74. struct mbuf *bp;
  75. {
  76. struct mbuf *dup;
  77.  
  78.     if (dup_p (&dup, bp, 6, 2) != 2)
  79.         return 0;
  80.     return ((int16)pull16 (&dup));
  81. }
  82.  
  83.